import { notFound } from 'next/navigation';
import fs from 'fs/promises';
import path from 'path';
import { Content } from 'antd/es/layout/layout';
import { BlogPostParams } from '@/types/blog';
import { mdxComponents } from '@/components/mdx-components'

interface BlogPostPageProps {
  params: Promise<BlogPostParams>;
}

async function getAllSlugs(): Promise<BlogPostParams[]> {
  try {
    const blogDir = path.join(process.cwd(), 'src', 'content', 'blog');
    const stacks = await fs.readdir(blogDir);
    
    const allSlugs: BlogPostParams[] = [];
    
    for (const stack of stacks) {
      const stackDir = path.join(blogDir, stack);
      const stackStat = await fs.stat(stackDir);
      if (!stackStat.isDirectory()) continue;
      
      const categories = await fs.readdir(stackDir);
      
      for (const category of categories) {
        const categoryDir = path.join(stackDir, category);
        const categoryStat = await fs.stat(categoryDir);
        if (!categoryStat.isDirectory()) continue;
        
        const files = await fs.readdir(categoryDir);
        const mdxFiles = files.filter(file => file.endsWith('.mdx'));
        
        mdxFiles.forEach(file => {
          allSlugs.push({
            stack: stack,
            category: category,
            slug: file.replace(/\.mdx$/, '')
          });
        });
      }
    }
    
    return allSlugs;
  } catch {
    return [];
  }
}

export async function generateStaticParams() {
  const slugs = await getAllSlugs();
  
  return slugs.map(({ stack, category, slug }) => ({
    stack: stack,
    category: category,
    slug: slug,
  }));
}

export default async function BlogPostPage({ params }: BlogPostPageProps) {
  const { stack, category, slug } = await params;
  
  try {
    const { default: MDXContent } = await import(`@/content/blog/${stack}/${category}/${slug}.mdx`);
    
    return (
      <Content style={{ padding: '0 48px' }}>
          <article className="prose max-w-none prose-sm mx-auto px-4 py-8"><MDXContent components={mdxComponents} /></article>
      </Content>
    );
  } catch {
    notFound();
  }
}